package com.tlgen.rpc.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ScanUtils {

    public static List<String> getClassesWithAnnotation(Class<? extends Annotation> annotationType) {
        List<String> classNames = new ArrayList<>();
        String localDirectory = System.getProperty("user.dir") + "\\src\\main\\java";
        File filePath = new File(localDirectory);
        List<File> aFiles = new ArrayList<>();
        getAllFile(filePath, aFiles);
        aFiles = aFiles.stream().filter(x -> x.getName().contains(".java")).collect(Collectors.toList());
        try {
            for (File aFile : aFiles) {
                String absolutePath = aFile.getAbsolutePath();
                String className = absolutePath
                        .substring(absolutePath.indexOf("\\java") + 6, absolutePath.lastIndexOf(".java"))
                        .replaceAll("\\\\", ".");
                if (!checkComment(absolutePath)) {
                    Class<?> clazz = Class.forName(className);
                    Annotation[] annotations = clazz.getAnnotationsByType(annotationType);
                    if (annotations.length > 0) {
                        classNames.add(clazz.getName());
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return classNames;
    }

    /**
     * 当前目录下的所有文件-不包括目录-递归方法
     *
     * @param fileList
     */
    private static void getAllFile(File file, List<File> fileList) {
        if (file.isDirectory()) {
            for (File listFile : Objects.requireNonNull(file.listFiles())) {
                getAllFile(listFile, fileList);
            }
        } else {
            fileList.add(file);
        }
    }


    public static boolean checkComment(String filePath) {
        boolean hasComments = false; // 标记变量，初始值为false
        try {
            FileReader reader = new FileReader(new File(filePath));
            BufferedReader bufferedReader = new BufferedReader(reader);
            Pattern pattern = Pattern.compile("//.*package"); // 创建正则表达式对象，匹配双斜线后的所有字符（包括换行）
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    hasComments = true; // 若发现了注释，将hasComments设置为true
                    break; // 只需查找到第一条注释就结束循环
                }
            }
            bufferedReader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return hasComments;
    }

}
